import service from '@/utils/request'
import {  Message, Loading } from 'element-ui'

let timer;
let downloadLoadingInstance;
export function excelExportApi(queryParams,urlStr){

  excelDownLoad(queryParams,urlStr).then((response) => {
    downLoadForTime(response.data,urlStr)
  });

}

function excelDownLoad(params,urlStr) {
  return service({
    url: urlStr +'/system/excel/export',
    method: 'get',
    params
  })
}

function downLoadForTime(data,urlstr) {
  let url =  urlstr + '/system/excel/downLoad?id=' + data;
    downLoad(url);
    timer = setInterval(() => {
    downLoad(url);
  }, 1000 * 1);
};

 function downLoad(url) {
  downloadLoadingInstance = Loading.service({ text: "正在下载数据，请稍后...", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
  
  return service.get(url,
     {
      responseType: 'blob' 
     }).then(async (data,res) => {

      let type = data.headers['content-type'];

        if( type.indexOf("vnd.ms-excel") != -1){
          clearInterval(timer);

          let filename = data.headers['content-disposition'];
          filename = filename.substr(filename.lastIndexOf("=") + 1);
          filename = decodeURI(filename);
          export_excel_file(data.data,filename);
          downloadLoadingInstance.close();
        }
        
  }).catch((r) => {
    console.log('错误',r);
    // Message.error('下载文件出现错误，请联系管理员！')
    clearInterval(timer);
    downloadLoadingInstance.close();
  })
}
 
 function export_excel_file(export_data, list_name) {
   let link = document.createElement("a");
   //    type就是blob的type,是MIME类型的，可以自己查看MIME类型都有哪些
   let blogw = new Blob([export_data], {
     type: "text/plain;charset=uft-8"
   })
   let objectUrl = window.URL.createObjectURL(blogw); //创建一个新的url对象
   link.href = objectUrl;
   link.download = list_name; //  下载的时候自定义的文件名
   link.click();
   window.URL.revokeObjectURL(objectUrl); //为了更好地性能和内存使用状况，应该在适当的时候释放url.
 }